<?php

/**
 * 芸瑞供应商 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopyunrui;
use App\Model\PssModel\ServiceConfig;
use App\Service\Code\Normal;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
class ShopyunruiApiClient
{
    private $account  = 'Shopyunrui';
    protected $config;
    protected $RouteMap = [
        'createOrder'   => '/gs/api/extOrderV2',
    ];
    
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //商品下单组
        $orderItem = [];
        $productAmt     = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item ) 
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity;
            
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            //商品组
            $orderItem[] = [
                "productName"   => $item['goods_name'],
                "barcode"       => $item['supplier_skucode'],
                "price"         => $singleGoodsPrice,
                "quantity"      => $buyAcount,
            ];
            $singleGoodsTotalPrice = bcmul((string)$singleGoodsPrice,(string)$buyAcount);
            $productAmt = bcadd((string)$productAmt,(string)$singleGoodsTotalPrice);
        }
        
        //实际下单金额 
        $real_total_money   = bcmul($orderInfo['real_total_money'],'100');
        //运费
        $deliver_money      = bcmul($orderInfo['deliver_money'],'100');
        //订单优惠金额 = 含税商品总金额  + 运费 -实际下单金额 
        $order_total_money  = bcadd((string)$productAmt,(string)$deliver_money);
        //优惠金额
        $discount_money     = bcsub((string)$order_total_money,(string)$real_total_money);
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$payTime);     
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $orderInfo['pay_sn'];
        
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        
        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        $order_sn = $orderInfo['supplier_dsn'];
        //请求数据
        $data = [
            'extOrderNo'    => $order_sn,
            'products'      => $orderItem,
            'customer'      => [
                "name"          => $orderInfo['receive_name'],
                "province"      => $orderInfo['province'],
                "city"          => $orderInfo['city'],
                "area"          => $orderInfo['district'],
                "address"       => $orderInfo['receive_address'],
                "idCard"        => $orderInfo['buyer_idcard'],
                "mobile"        => $orderInfo['recveive_phone']
            ],
            'paymentInfo'  => [
                'platform'      => $PayCompanyCode,
                'amount'        => $real_total_money,
                'currency'      => 'RMB',
                'transactionId' => $pay_sn,
                'datePaid'      => $pay_time
            ],
            'customInfo'    => [
                "buyerIdCard"   => $orderInfo['buyer_idcard'],
                "buyerName"     => $orderInfo['buyer_realname'],
                "customOrderNo" => $order_sn,
                "orderTime"     => date("Y-m-d H:i:s"),
                "platformCode"  => $enterpriseNum,
                "platformName"  => $enterpriseName,
                "currency"      => "RMB",
                "orderPrice"    => $order_total_money,
                "deliverFee"    => $deliver_money,
                "discount"      => 0,
                "coupon"        => $discount_money
            ],
            'notes'     => ''
        ];
        
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        
        $result = $this->execute($requestParam);
        if( $result['code'] == Normal::SUC ) 
        {
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $result['data']['data']['orderNo']
            ]);
        }
        
        return $result;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        $data = [
        ];
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( array $param = [] )
    {
       $timestamp = getmsectime();
       return [
           'sign'       => md5($this->config['key'].$timestamp.$this->config['apiSecret']),
           'timestamp'  => $timestamp,
       ];
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        
        $method = $param['method'];
        $sign_arr = $this->getSign($param['data']);
        $url = $this->config['Endpoint'].$this->RouteMap[$method]."?key={$this->config['key']}&timestamp={$sign_arr['timestamp']}&sign={$sign_arr['sign']}";
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => ["Content-Type: application/json"],
        
            ],
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['code']) && $resHttp['code'] == '200' && isset($resHttp['success']) && $resHttp['success'] == true ) {
            return Normal::returnCode(Normal::SUC,"成功",$resHttp);
        }
        
        return Normal::returnCode(Normal::FAIL,$res);
    }
}